package com.itheima.reggie.controlller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.DTO.DishDto;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.impl.CategoryService;
import com.itheima.reggie.service.impl.DishFlavorService;
import com.itheima.reggie.service.impl.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("/dish")
public class DishControlloer {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody  DishDto dishDto) {
        log.info("save dish : {}", dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> getDish(int page,int pageSize,String name){
        //构造分页对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name!=null,Dish::getName, name);//如果不为空 那么 wherer Dish::getName=name 否则查询全部
        queryWrapper.orderByDesc(Dish::getUpdateTime);//过滤条件 按更新时间排序
        dishService.page(pageInfo, queryWrapper);//拿着这个page对象 取分页
        //由于Dish没有菜品分类  所以发往前端的pageinfo没有这个 只有分类的id
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records"); //pageinfo(原page)-> dishDtopage(新page)
//      封装在page里面的数据就是一个records集合对象 我们拿着records再去找categroyName
        List<Dish> records=pageInfo.getRecords();

        List<DishDto> list=records.stream().map((item)->{
            //因为DishDto里面有 categroyName
            DishDto dishDto=new DishDto();

            BeanUtils.copyProperties(item,dishDto); //属性赋值 把dish里面的属性 给 ->>dishdto
            /*拿到 Dish里面 存储的id 然后根据id去查询name 再赋值给 DTO*/
            Long categoryId=item.getCategoryId();
            Category category = categoryService.getById(categoryId); //有的categroyID存在 但是根据这个id找不到Name
            if(category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> GetupdateDishData(@PathVariable Long id) {
        DishDto byIdwithFlavor = dishService.getByIdwithFlavor(id);
        return R.success(byIdwithFlavor);
    }


    @PutMapping
    public R<String> updateDishsubmit(@RequestBody  DishDto dishDto) {
       //设置两张表的更新
        dishService.updateWithFlavor(dishDto);

        //TODO 清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("修改菜品成功");
    }

    @PostMapping("/status/{status}")
    public R<String> updatestatus(@PathVariable Integer status,Long ids,HttpServletRequest request) {
        Dish dish=new Dish();
        dish.setId(ids);
        dish.setStatus(status);
        Long empId = (Long)request.getSession().getAttribute("employee");
        dish.setUpdateUser(empId);
        log.info("id={}，status={},当前user_id={}",ids,status, request.getSession().getAttribute("employee"));


        dishService.updateById(dish);
        return R.success("状态更新成功");
    }


    /**
     * 根据条件查询菜品数据
     * @param dish
     * @return
     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish) {
//        //构造查询条件
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        //添加条件 状态为启售状态
//        queryWrapper.eq(Dish::getStatus, 1);
//        List<Dish> list = dishService.list(queryWrapper);
//
//        return R.success(list);
//    }
    /**
     * 移动端返回数据
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtolist = null;
        //动态构造key
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //TODO 先从redis中获取缓存数据
        dishDtolist = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //TODO 如果存在 ，则直接返回 无需查询数据库
        if (dishDtolist!=null) {
            return R.success(dishDtolist);
        }

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //添加条件 状态为启售状态
        queryWrapper.eq(Dish::getStatus, 1);

        List<Dish> list = dishService.list(queryWrapper);

         dishDtolist = list.stream().map((item)->{
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId=item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if(category!=null){{
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }}
            //当前菜品的id
            Long dishid=item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId, dishid);
            //select *from dish_flavor where dish_id=？
            List<DishFlavor> flavors = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());
        //TODO 如果不存在，则查询数据库 将查询到的菜品数据缓存到redis
        redisTemplate.opsForValue().set(key,dishDtolist,60, TimeUnit.MICROSECONDS);
        return R.success(dishDtolist);
    }




}
